<template>
  <Modal
      :show="show"
      title="用户授权"
      @ok="handleOk"
      @cancel="handleCancel"
  >
    <n-data-table
      :columns="roleUserModalColums"
      :data="tableData"
      :row-key="rowKey"
      :checked-row-keys="rowKeys"
      @update:checked-row-keys="handleCheck"
    ></n-data-table>
  </Modal>
</template>

<script lang="ts">
export default {
  name: "RoleUserModal"
}
</script>

<script setup lang="ts">
import {onMounted, ref} from "vue"
import Modal from '@/components/Modal.vue'
import {ums_role_userImpower, ums_user_queryList} from '@/api/ums'
import {RoleListType, roleUserModalColums} from '@/view/system/role/RoleType'
import {UserType} from '@/type/ums'
import useMsg from '@/hooks/useMsg'

const {success, error} = useMsg()

const show = ref<boolean>(false)

const tableData = ref<UserType[]>([])

const rowKeys = ref<number[]>([])

const rowKey = (row:UserType) => row.id

const formData = ref<RoleListType>()

const handleOk = () => {
  const list = rowKeys.value.map(item => ({
    userId: item,
    roleId: formData.value!.roleId
  }))
  ums_role_userImpower({
    list,
    roleId: formData.value!.roleId
  }).then(res => {
    if (res.code === 200){
      show.value = false
      success(res.message)
    }else{
      show.value = false
      error(res.message)
    }
  })
}

const handleCancel = () => {
  show.value = false
}

const handleCheck = (rows: number[]) => {
  rowKeys.value = rows
}

function init (data:UserType[], row: RoleListType) {
  rowKeys.value = []
  tableData.value = []
  formData.value = undefined
  ums_user_queryList().then(res => {
    if (res.code === 200) {
      show.value = true
      tableData.value = res.data
      rowKeys.value = data.map(item => item.id)
      formData.value = row
    }else {
      error(res.message)
    }
  })
}

defineExpose({
  init
})

onMounted( () => {
} )
</script>

<style scoped lang="scss">

</style>
